import axios from 'axios';
import qs from 'qs';
let grovider = 'mtoken_gm3000';
let skfDevicesValue = '';
let skfContainersValue = ''; // 当前设备
// 外部签名私钥
let extPrivateKeyValueKey = 'SGD_SM3';
// 指定数字证书
let specifyCertificate = '';
let extPrivateKeyValue =
  'MIGHAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBG0wawIBAQQgIeArCKJfGmiK3rgIj0XIpEIZc4ASIfGTVVQjUoLm9xyhRANCAAReMZwBl3YFxREAnb3Priwm3/NDev3pA58FlQmv+YJlQy2EOJF1X/pxFbhj1m3VjNfY70ZKHBBbpvR//UJknWxc';
// ukey私钥
let skfHashalg = 'SGD_SM3';
let skfHashalgValue = ''; // 待签名数据
let skfVerifySignatureP1Value = '';
let subjectDN = ''; //证书DN
// 证书剩余有效时间

// 获取uKey信息
let publicEnum = (param, that) => {
  var baseUrl = param.baseUrl || 'https://local.mcsca.com.cn:2443';
  return new Promise(function(resolve) {
    axios({
      method: 'post',
      url: baseUrl + param.url,
      data: qs.stringify(param.data),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    })
      .then((data) => {
        resolve(data.data);
      })
      .catch((err) => {
        if (String(err).indexOf('Network Error')) {
          that
            .$confirm('未检测到ukey驱动请下载驱动', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              cancelButtonClass: 'default-btn',
              confirmButtonClass: 'primary-btn',
              type: 'warning',
            })
            .then(() => {});
        }
      });
  });
};
let success = (msg, that) => {
  that.$message({
    message: msg,
    type: 'success',
  });
};
// 公钥验签
let skfVerifySignatureP1 = (that) => {
  return publicEnum({
    url: '/skf/ukeyverify',
    data: {
      provider: grovider,
      devname: skfDevicesValue,
      vecname: skfContainersValue,
      hashalg: skfHashalg,
      data: skfHashalgValue,
      signature: skfVerifySignatureP1Value,
    },
  }).then((result) => {
    if (result.status !== 200) {
      that.$message.error(result.message);
      return;
    }
    success(result.message, that);
    return true;
  });
};
// 外部签名私钥
let skfExtKeySignData = (that) => {
  return publicEnum({
    url: '/skf/ukeysigndata',
    data: {
      provider: grovider,
      prvKey: extPrivateKeyValue,
      data: skfHashalgValue,
      hashalg: extPrivateKeyValueKey,
    },
  })
    .then((result) => {
      if (result.status !== 200) {
        that.$message.error(result.message);
        return;
      }
      // success('外部签名私钥获取成功', that);
      skfVerifySignatureP1Value = result.signature;
      // return usbKeySignData(that)
    })
    .catch(() => {
      that.$message.error('外部签名私钥异常！');
    });
};
// 数据验签 USBkey
let usbKeySignData = (that, data) => {
  return publicEnum({
    url: '/skf/ukeysigndata',
    data: {
      provider: grovider,
      devname: skfDevicesValue,
      vecname: skfContainersValue,
      data: JSON.stringify(data),
      hashalg: skfHashalg,
    },
  }).then((result) => {
    if (result.status !== 200) {
      that.$message.error(result.message);
      return;
    }
    skfVerifySignatureP1Value = result.signature;
    return result;
  });
};
// 生成P10-生成证书请求
let skfGenSignCSR = (that) => {
  return publicEnum({
    url: '/skf/gensigncsr',
    data: {
      provider: grovider,
      devname: skfDevicesValue,
      vecname: skfContainersValue,
    },
  }).then((result) => {
    if (result.status !== 200) {
      that.$message.error(result.message);
      return;
    }
    return result;
  });
};
// 默认是获取设备列表第一个
let skfEnumContainer = (that) => {
  publicEnum({
    url: '/skf/enumcontainer',
    data: {
      provider: grovider,
      devname: skfDevicesValue, // 设备列表  当前选中
    },
  }).then((result) => {
    if (result.status !== 200) {
      that.$message.error(result.message);
    } else {
      skfContainersValue = result.data.split('@##@')[0];
    }
  });
};
// 证书登录
let skfCertLogin = (that) => {
  publicEnum({
    url: '/skf/certlogin',
    data: {
      provider: grovider,
      subject: subjectDN,
      nonce: '5A1412723403F1E3AA7001A3',
      attached: 1,
    },
  }).then((result) => {
    if (result.status !== 200) {
      that.$message.error(result.message);
    } else {
      return result;
    }
  });
};
// 导出指定数字证书
let exportCertificate = (that) => {
  return publicEnum({
    url: '/skf/exportcertificate',
    data: {
      provider: grovider,
      devname: skfDevicesValue,
      vecname: skfContainersValue,
      sign: 1,
    },
  }).then((result) => {
    if (result.status !== 200) {
      that.$message.error(result.message);
    } else {
      specifyCertificate = result.data;
      return true;
    }
  });
};
// 枚举证书DN
let getEnumcertificate = (that) => {
  return publicEnum({
    url: '/skf/enumcertificate',
    data: {
      provider: grovider,
      devname: skfDevicesValue,
    },
  }).then((result) => {
    if (result.status !== 200) {
      that.$message.error(result.message);
    } else {
      return result;
    }
  });
};
// 获取证书信息
let getCertInfo = (that) => {
  return exportCertificate(that).then((res) => {
    if (res) {
      return publicEnum({
        url: '/util/getcertinfo',
        data: {
          cert: specifyCertificate,
        },
      }).then((result) => {
        if (result.status !== 200) {
          that.$message.error(result.message);
        } else {
          return result;
        }
      });
    } else {
      return '网络异常';
    }
  });
};
// 获取设备信息
let getDevInfo = (that) => {
  return publicEnum({
    url: '/skf/getdevinfo',
    data: {
      provider: grovider,
      devname: skfDevicesValue,
    },
  }).then((result) => {
    if (result.status !== 200) {
      that.$message.error(result.message);
    } else {
      return result;
    }
  });
};
// pin码效验
let verifyPIN = (that, pin, isDn = false) => {
  return publicEnum({
    url: '/skf/verifypin',
    data: {
      provider: grovider,
      devname: skfDevicesValue, // 设备列表  当前选中
      pin: pin, // 用户输入的密码
    },
  })
    .then((result) => {
      if (result.status !== 200) {
        that.$message.error(result.message + '\r\n剩余重试次数:' + result.RemainRetryCount);
        return result.message == '校验PIN成功';
      }
      if (isDn) {
        publicEnum({
          url: '/skf/verifypin',
          data: {
            provider: grovider,
            devname: skfDevicesValue, // 设备列表  当前选中
            pin: pin, // 用户输入的密码
          },
        }).then((certs) => {
          if (certs.status !== 200) {
            that.$message.error('登陆异常！', certs.message);
            return;
          }
          var today = new Date();
          var notAfter = new Date(certs.certs[0].notAfter.replace('-', '/'));
          // var remainDays = Math.ceil((notAfter - today) / (1000 * 60 * 60 * 24));
          subjectDN = certs.certs[0].subjectDN;
          return { subjectDN: subjectDN, isPIN: true };
        });
      } else {
        return true;
      }
    })
    .catch(function(error) {
      that.$message.error('登陆异常！', error);
    });
};
// 枚举当前是否有设备
let judgeOneEnv = (that) => {
  return publicEnum(
    {
      url: '/skf/enumdev',
      data: {
        provider: grovider,
      },
    },
    that,
  )
    .then((result) => {
      if (result.status === 500) {
        that.$message.error('USB Key驱动未安装!');
        return false;
      } else if (result.status === 404) {
        that.$message.error('USB Key未插入!');
        return false;
      } else if (result.status === 200) {
        // success('获取设备成功', that);
        skfDevicesValue = result.data.split('@##@')[0];
        skfEnumContainer(that);
        return true;
      }
    })
    .catch((error) => {
      that.$message.error('UKey插件服务异常！', error);
    });
};

export {
  judgeOneEnv,
  verifyPIN,
  usbKeySignData,
  skfExtKeySignData,
  skfVerifySignatureP1,
  skfGenSignCSR,
  skfCertLogin,
  exportCertificate,
  getCertInfo,
  getDevInfo,
  getEnumcertificate,
};
